package com.example.hello.mapper;

import com.example.hello.pojo.CommentResponse;
import com.example.hello.pojo.CommunityComment;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface CommunityCommentMapper {

    /** 根评论：parent_id IS NULL */
    @Select("""
      SELECT 
        c.id,
        c.user_id      AS userId,
        u.avatar       AS userAvatar,
        u.nickname     AS userNickname,
        c.parent_id    AS parentId,
        c.to_user_id   AS toUserId,
        u2.nickname    AS toUserNickname,
        c.content,
        DATE_FORMAT(c.created_at, '%Y-%m-%dT%H:%i:%s') AS createdAt
      FROM community_comment c
      LEFT JOIN `user` u  ON c.user_id    = u.id
      LEFT JOIN `user` u2 ON c.to_user_id = u2.id
      WHERE c.parent_id IS NULL
      ORDER BY c.created_at DESC
      LIMIT #{offset},#{limit}
      """)
    List<CommentResponse> selectRootComments(
            @Param("offset") int offset,
            @Param("limit")  int limit
    );

    /** 回复：parent_id = #{rootId} */
    @Select("""
      SELECT 
        c.id,
        c.user_id      AS userId,
        u.avatar       AS userAvatar,
        u.nickname     AS userNickname,
        c.parent_id    AS parentId,
        c.to_user_id   AS toUserId,
        u2.nickname    AS toUserNickname,
        c.content,
        DATE_FORMAT(c.created_at, '%Y-%m-%dT%H:%i:%s') AS createdAt
      FROM community_comment c
      LEFT JOIN `user` u  ON c.user_id    = u.id
      LEFT JOIN `user` u2 ON c.to_user_id = u2.id
      WHERE c.parent_id = #{rootId}
      ORDER BY c.created_at ASC
      """)
    List<CommentResponse> selectReplies(@Param("rootId") Long rootId);

    @Insert("INSERT INTO community_comment(user_id, parent_id, to_user_id, content) " +
            "VALUES(#{userId}, #{parentId}, #{toUserId}, #{content})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(CommentResponse comment);

    @Delete("DELETE FROM community_comment WHERE id = #{id}")
    int deleteById(@Param("id") Long id);
}